package cn.edu.zime.tjh.gui;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientGUIHandler extends ChannelInboundHandlerAdapter {
    private final ClientGUIApp clientApp;
    
    public ClientGUIHandler(ClientGUIApp clientApp) {
        this.clientApp = clientApp;
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String message = (String) msg;
        
        // 根据消息类型显示不同的标识
        String messageType;
        if (message.startsWith("[Server Broadcast]:")) {
            messageType = "BROADCAST";
            message = message.substring("[Server Broadcast]: ".length());
        } else if (message.startsWith("[Server Message]:")) {
            messageType = "SERVER";
            message = message.substring("[Server Message]: ".length());
        } else {
            messageType = "RECEIVED";
        }
        
        clientApp.showMessage(message, messageType);
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        clientApp.showMessage("Connection lost", "SYSTEM");
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        clientApp.showMessage("Error: " + cause.getMessage(), "ERROR");
        ctx.close();
    }
}